import { Card, Input, App, Button } from 'antd';
import { RcFile } from 'antd/es/upload';
import React, { useState, useEffect, useRef, useImperativeHandle } from 'react';
import { useLocation } from 'react-router-dom';

import mcpService from '@/api/services/mcpService';
import { GetCategoriesListRes, GetCreatedMcpListItem } from '@/common/types';
import AuthModal from '@/components/auth-modal/auth-modal';
import { SimpleEditableSelect } from '@/components/eai-design/select';
import { SvgIcon } from '@/components/icon';
import { DEFAULT_IMAGES } from '@/components/work-modal/components/ImageDisplay';
import LogoSelector from '@/components/work-modal/components/LogoSelector';
import useModal from '@/hooks/use-modal/useModal';
import { MongoImageTypeEnum } from '@/pages/chat/tools/constants';
import { compressImgFileAndUpload } from '@/types/app/api';
import { convertHeaderAuthToFormData } from '@/utils/auth';

import type { UploadProps } from 'antd';

const BasicInfo = React.forwardRef<
  {
    getFormData: () => Record<string, any>;
  },
  {
    className?: string;
    itemData?: GetCreatedMcpListItem;
    onSubmit?: (data: Record<string, any>) => void;
    onValidationChange?: (isValid: boolean) => void;
  }
>(({ className = '', itemData, onSubmit, onValidationChange }, ref) => {
  const { message } = App.useApp();
  const location = useLocation();
  const isSubmitting = useRef(false);
  const modal = useModal('input');
  const [logoLoading, setLogoLoading] = useState(false);
  const [sceneImageLoading, setSceneImageLoading] = useState(false);
  const [customLogos, setCustomLogos] = useState<string[]>([]);
  const [customSceneImages, setCustomSceneImages] = useState<string[]>([]);
  const [selectedLogo, setSelectedLogo] = useState<string>('');
  const [authData, setAuthData] = useState<string>('');
  const [currentAuthConfig, setCurrentAuthConfig] = useState<any>({});
  const [avatarImages, setAvatarImages] = useState<string[]>([]);

  // 判断是否显示基础信息样式
  const showBasicInfoStyle = !!(itemData?.type ? itemData?.templateId : itemData?.id);

  // 统一的获取表单数据方法
  const getFormData = () => {
    const envFields = itemData?.envSchema?.properties
      ? Object.keys(itemData.envSchema.properties)
      : [];

    const variables = envFields.reduce((acc, field) => {
      acc[field] = formValues[field];
      return acc;
    }, {} as Record<string, any>);

    return {
      url,
      headerAuth: formValues.headerAuth,
      templateId: itemData?.type ? itemData?.templateId : itemData?.id,
      variables,
      id: formValues?.id,
      name: formValues.name,
      avatar: selectedLogo,
      avatarImages,
      description: formValues.description,
      categoryCN: selectedCategory,
      tools: [],
    };
  };

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    getFormData,
  }));

  // 表单状态管理 - 新增name和description初始化
  const [formValues, setFormValues] = useState<Record<string, any>>({
    name: '',
    description: '',
    headerAuth: {},
    ...(itemData?.envSchema?.properties
      ? Object.keys(itemData.envSchema.properties).reduce((acc, key) => {
        acc[key] = '';
        return acc;
      }, {} as Record<string, any>)
      : {}),
  });

  const [categoriesData, setCategoriesData] = useState<GetCategoriesListRes[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [url, setUrl] = useState<string>('');

  // 初始化表单数据
  useEffect(() => {
    if (itemData?.envSchema?.properties) {
      const initialValues = Object.keys(itemData.envSchema.properties).reduce((acc, key) => {
        acc[key] = '';
        return acc;
      }, {} as Record<string, any>);

      setFormValues((prev) => ({ ...prev, ...initialValues }));
    }

    // 编辑状态：回显已有数据
    if (itemData?.updateTime) {
      const itemDataAny = itemData as any; // 类型断言，因为编辑状态的数据结构可能不同
      setFormValues((prev) => ({
        ...prev,
        name: itemDataAny.name || '',
        description: itemDataAny.description || '',
        headerAuth: itemDataAny.headerAuth || {},
        id: itemDataAny.id,
        ...(itemDataAny.variables || {}),
      }));
      setSelectedLogo(itemDataAny.avatar || '');
      setAvatarImages(itemDataAny.avatarImages || []);
      setSelectedCategory(itemDataAny.categoryCN || '');
      setCustomLogos(itemDataAny.avatarImages || []);
      setUrl(itemDataAny.url || '');
      setCurrentAuthConfig(itemDataAny.headerAuth || {});

      // 设置鉴权显示数据
      if (itemDataAny.headerAuth && Object.keys(itemDataAny.headerAuth).length > 0) {
        const authType = Object.keys(itemDataAny.headerAuth)[0];
        if (authType === 'Basic' || authType === 'Bearer') {
          setAuthData(authType);
        } else {
          setAuthData('自定义');
        }
      } else {
        setAuthData('无');
      }
    } else {
      const itemDataAny = itemData as any;
      setFormValues((prev) => ({
        ...prev,
        name: itemDataAny?.name || '',
        description: itemDataAny?.description || '',
        categoryCN: itemDataAny?.categoryCN || '',
      }));
      setSelectedLogo(itemDataAny?.avatar || '');
      setAvatarImages(itemDataAny?.avatar ? [itemDataAny?.avatar] : []);
      setCustomLogos(itemDataAny?.avatar ? [itemDataAny?.avatar] : []);
      setSelectedCategory(itemDataAny?.categoryCN || '');
    }
  }, [itemData]);

  // 获取分类列表
  useEffect(() => {
    const getCategoriesList = async () => {
      try {
        const res = await mcpService.getCategoriesList();
        const options = res.map((item: any) => ({
          label: item.nameCN,
          value: item.nameCN,
          id: item.id,
          type: item.type,
        }));
        setCategoriesData(options as any);
      } catch (error) {
        message.error('获取分类列表失败');
      }
    };

    getCategoriesList();
  }, []);

  // 表单字段变更处理
  const handleFieldChange = (fieldName: string, value: any) => {
    setFormValues((prev) => ({ ...prev, [fieldName]: value }));
  };

  // 鉴权配置
  const handleSetting = () => {
    modal.input.open();
  };
  const handleAuthSubmit = (value: object) => {
    setCurrentAuthConfig(value);

    if (Object.keys(value).length === 0) {
      setFormValues((prev) => ({ ...prev, headerAuth: {} }));
      setAuthData('无');
    } else {
      const authType = Object.keys(value)[0];
      if (authType === 'Bearer' || authType === 'Basic') {
        setAuthData(authType);
      } else {
        setAuthData('自定义');
      }

      if (authType === 'Basic') {
        const basicValue = value as any;
        const credentials = `${basicValue.Basic.username}:${basicValue.Basic.password}`;
        const base64Credentials = Buffer.from(credentials).toString('base64');
        const newHeaderAuth = {
          Basic: {
            ...basicValue.Basic,
            value: base64Credentials,
          },
        };
        setFormValues((prev) => ({ ...prev, headerAuth: newHeaderAuth }));
      } else {
        setFormValues((prev) => ({ ...prev, headerAuth: value }));
      }
    }
    modal.input.close();
  };
  // 提交表单数据
  const handleSubmitClick = async () => {
    if (isSubmitting.current) return;
    const templateId = itemData?.type ? itemData?.templateId : itemData?.id;

    if (templateId) {
      if (itemData?.envSchema?.required?.length) {
        const missingFields = itemData.envSchema.required.filter(
          (field) => !formValues[field]?.trim(),
        );

        if (missingFields.length) {
          message.warning(`请填写必填字段: ${missingFields.join(', ')}`);
          return;
        }
      }
    } else if (!url) {
      message.warning('请输入MCP地址');
      return;
    }

    try {
      isSubmitting.current = true;
      // message.loading('提交中...', 0);

      const submitData = getFormData();
      // 通知父组件
      if (onSubmit) {
        onSubmit(submitData);
      }

      // message.success('连接成功');
    } catch (error) {
      message.error('连接失败，请重试');
      console.error('提交错误:', error);
    } finally {
      isSubmitting.current = false;
    }
  };

  // 检查是否所有必填项已填写（用于表单验证）
  const isAllRequiredFilled = () => {
    if (!formValues.name || !selectedCategory || !selectedLogo) return false;
    const templateId = itemData?.type ? itemData?.templateId : itemData?.id;
    if (templateId) {
      if (itemData?.envSchema?.required?.length) {
        return itemData?.envSchema?.required.every((field) => formValues[field]?.trim());
      }
      return true;
    }
    if (!url) return false;
    return true;
  };

  // 连接按钮是否可点击（只需要地址和鉴权配置）
  const isConnect = () => {
    const templateId = itemData?.type ? itemData?.templateId : itemData?.id;

    if (templateId) {
      // 如果有环境变量配置，需要填写所有必填字段
      if (itemData?.envSchema?.required?.length) {
        return itemData.envSchema.required.every((field) => formValues[field]?.trim());
      }
      return true;
    }
    // 如果没有环境变量配置，只需要填写地址
    if (!url) return false;
    return true;
  };

  // 监听验证状态变化并通知父组件
  useEffect(() => {
    const isValid = isAllRequiredFilled();
    onValidationChange?.(isValid);
  }, [
    formValues,
    selectedCategory,
    selectedLogo,
    url,
    itemData,
    onValidationChange,
    message,
    isAllRequiredFilled,
  ]);

  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith('image/');
    const arr = file.name.split('.');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return false;
    }
    if (!['png', 'jpg', 'jpeg', 'svg'].includes(arr[arr.length - 1])) {
      message.error('不支持该文件类型！');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB！');
      return false;
    }
    return true;
  };

  const logoBeforeUpload = (file: RcFile) => {
    if (!beforeUpload(file)) {
      return false;
    }
    if (customLogos.filter((logo) => !Object.keys(DEFAULT_IMAGES).includes(logo)).length >= 2) {
      message.warning('最多只能上传2张图片，请先删除已有图片。');
      return false;
    }
    return true;
  };

  const logoUploadProps: UploadProps = {
    name: 'file',
    showUploadList: false,
    accept: '.png,.jpg,.jpeg,.svg',
    beforeUpload: logoBeforeUpload,
    customRequest: ({ file }) => handleLogoUpload(file as File),
  };

  const handleLogoUpload = async (file: File) => {
    setLogoLoading(true);
    try {
      const src = await compressImgFileAndUpload({
        type: MongoImageTypeEnum.appAvatar,
        file,
        maxW: 300,
        maxH: 300,
      });
      const url = new URL(src);
      const path = url.pathname.replace('//', '/');
      setCustomLogos((prev) => [path, ...prev]);
      setAvatarImages((prev) => [path, ...prev]);
      message.success('Logo上传成功');
    } catch (error) {
      message.error('Logo上传失败');
    } finally {
      setLogoLoading(false);
    }
  };

  const handleLogoSelect = (url: string) => {
    setSelectedLogo(url); // 更新选中的LOGO
  };

  const handleLogoDelete = (logoUrl: string) => {
    setCustomLogos((prev) => prev.filter((url) => url !== logoUrl));
    setAvatarImages((prev) => prev.filter((url) => url !== logoUrl)); // 新增：从avatarImages数组中删除
    if (selectedLogo === logoUrl) {
      setSelectedLogo(''); // 如果删除选中的LOGO，清空选择
    }
  };

  const handleTagOptionsChange = async (
    options: { label: string; value: string; id?: string }[],
    type: 'add' | 'delete',
  ) => {
    console.log('options', options, type);
    const addOptions = options.filter(
      (option) => !categoriesData.some((t) => t.value === option.value),
    );
    const deleteOptions = categoriesData.filter(
      (option) => !options.some((t) => t.value === option.value),
    );
    const option =
      type === 'add' ? addOptions[addOptions.length - 1] : deleteOptions[deleteOptions.length - 1];
    const res =
      type === 'add'
        ? await mcpService.createCategories(option.label)
        : await mcpService.deleteCategories(option.id ?? '');
    if (res) {
      type === 'add'
        ? setCategoriesData([
          ...categoriesData,
          { label: res.nameCN, value: res.nameCN, id: res.id },
        ])
        : setCategoriesData(categoriesData.filter((t) => t.id !== option.id));
      return true;
    }
    return false;
  };

  return (
    <Card
      className={`orch-card-body mb-4 h-full overflow-auto ${className}`}
      style={{ background: '#fff', border: 'none' }}
    >
      <div className="space-y-4">
        {showBasicInfoStyle && (
          <div className="flex items-center gap-2 border-b border-[var(--fill-quaternary)] pb-3">
            <SvgIcon icon="info-circle" size={20} color="#1B6DFA" />
            <div className="text-base font-semibold text-text-5">基础信息</div>
          </div>
        )}
        {/* MCP工具名称 */}
        <div className={showBasicInfoStyle ? 'ml-7' : ''}>
          <div className="mb-2 font-normal text-text-4">
            MCP工具名称
            <span className="ml-1 text-xs text-error">*</span>
          </div>
          <Input
            className="w-full focus:border-[#D9D9D9] focus:outline-none"
            value={formValues.name}
            onChange={(e) => handleFieldChange('name', e.target.value)}
            placeholder="为您的MCP工具命名"
            maxLength={20}
            showCount
          />
        </div>

        {/* MCP工具描述 */}
        <div className={showBasicInfoStyle ? 'ml-7' : ''}>
          <div className="mb-2 font-normal  text-text-4">MCP工具描述</div>
          <Input.TextArea
            className="w-full resize-none rounded-lg border p-2 focus:border-[#D9D9D9] focus:outline-none"
            maxLength={200}
            placeholder="输入MCP工具描述"
            value={formValues.description}
            onChange={(e) => handleFieldChange('description', e.target.value)}
            style={{ borderColor: '#D9D9D9', paddingBottom: '24px' }}
            autoSize={{ minRows: 2, maxRows: 6 }}
          />
        </div>

        {/* 应用Logo */}
        <div className={showBasicInfoStyle ? 'ml-7' : ''}>
          <LogoSelector
            showTip={false}
            titleName="MCP工具logo"
            appType="mcp"
            labelClassName="!font-normal"
            uploadedLogoUrl={selectedLogo}
            selectedLogoId={selectedLogo}
            customLogos={customLogos}
            loading={logoLoading}
            onSelect={handleLogoSelect}
            onDelete={handleLogoDelete}
            uploadProps={logoUploadProps}
          />
        </div>

        {/* MCP工具类型 */}
        <div className={showBasicInfoStyle ? 'ml-7' : ''}>
          <div className="mb-2 font-normal  text-text-4">
            MCP工具类型
            <span className="ml-1 text-xs text-error">*</span>
          </div>
          <SimpleEditableSelect
            className="w-full"
            showSearch
            value={selectedCategory}
            options={categoriesData as any}
            placeholder="请选择MCP工具类型"
            onOptionsChange={handleTagOptionsChange}
            onChange={(value) => setSelectedCategory(value)}
            allowAdd
            maxLength={20}
            addButtonText="添加MCP工具类型"
          />
        </div>

        {/* 鉴权配置 */}
        {!showBasicInfoStyle ? (
          <>
            {/* MCP地址 */}
            <div className={showBasicInfoStyle ? 'ml-7' : ''}>
              <div className="mb-2 font-normal  text-text-4">
                MCP地址
                <span className="ml-1 text-xs text-error">*</span>
              </div>
              <Input
                className="w-full focus:border-[#D9D9D9] focus:outline-none"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                placeholder="请输入MCP地址"
              />
            </div>
            <div className={showBasicInfoStyle ? 'ml-7' : ''}>
              <div>
                <div className="mb-2 text-text-4">鉴权配置</div>
                <div className="flex h-11 w-full items-center justify-between rounded-md bg-[var(--fill-quinary)] px-3 text-sm font-normal text-text-5">
                  <div>{authData || '无'}</div>
                  <div
                    className="flex cursor-pointer items-center gap-1 text-sm font-normal text-[var(--geekblue-6)]"
                    onClick={() => {
                      handleSetting();
                    }}
                  >
                    <SvgIcon icon="manage" size={16} />
                    设置
                  </div>
                </div>
              </div>
            </div>
          </>
        ) : (
          itemData?.envSchema?.properties && (
            <>
              <div className="flex items-center justify-between border-b border-[var(--fill-quaternary)] pt-2">
                <div className="flex items-center gap-2 pb-3 ">
                  <SvgIcon icon="mcp-circle" size={20} color="#1B6DFA" />
                  <div className="text-base font-semibold text-text-5">MCP参数</div>
                </div>
                <div
                  className="text-normal flex cursor-pointer items-center gap-1 text-[var(--geekblue-6)]"
                  onClick={() => window.open(itemData.tutorialUrl, '_blank')}
                >
                  <SvgIcon icon="help" size={16} color="#1B6DFA" />
                  <div>使用教程</div>
                </div>
              </div>
              {Object.entries(itemData?.envSchema?.properties || {}).map(
                ([fieldName, fieldConfig]) => (
                  <div key={fieldName} className="mb-4 ml-7">
                    <div className="mb-2 font-normal text-text-4">
                      {fieldName}
                      {itemData?.envSchema?.required?.includes(fieldName) && (
                        <span className="ml-1 text-xs text-error">*</span>
                      )}
                    </div>
                    <Input
                      className="w-full focus:border-[#D9D9D9] focus:outline-none"
                      value={formValues[fieldName]}
                      onChange={(e) => handleFieldChange(fieldName, e.target.value)}
                      placeholder={fieldConfig.description || `请输入${fieldName}`}
                    />
                  </div>
                ),
              )}
            </>
          )
        )}

        <div className="flex pt-4">
          <Button
            type="primary"
            className="w-full"
            onClick={handleSubmitClick}
            disabled={!isConnect()}
            loading={isSubmitting.current}
          >
            连接
          </Button>
        </div>
      </div>
      <AuthModal
        open={modal.input.isOpen}
        onCancel={modal.input.close}
        onSubmitOk={handleAuthSubmit}
        title="鉴权配置"
        defaultValue={convertHeaderAuthToFormData(currentAuthConfig)}
      />
    </Card>
  );
});

export default BasicInfo;
